import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { CallOption } from './call-option';

@Injectable({
  providedIn: 'root'
})
export class CallService {
  constructor(
    private win: Window,
    private loadingCtrl: LoadingController,
  ) { }

  async call(name: string, option: CallOption, ...args: any[]) {
    let loading;
    if (option.msg) {
      loading = await this.loadingCtrl.create({
        message: option.msg,
      });
      await loading.present();
    }

    if (name in this.win) {
      const ret = args.length > 0 ? await (this.win as any)[name](...args) : await (this.win as any)[name]();

      if (option.msg) {
        await loading.dismiss();
      }

      return ret;
    }

    console.log('call', name);

    if (option.msg) {
      await loading.dismiss();
    }

    return option.def;
  }
}
